package net.sourceforge.wurfl.core.request.normalizer.specific;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sourceforge.wurfl.core.request.normalizer.UserAgentNormalizer;

import org.apache.commons.lang.text.StrBuilder;

public class SafariNormalizer implements UserAgentNormalizer {

	
	private static final String REGEX = "(Mozilla\\/5\\.0.*U\\;)(.*?)(Safari\\/\\d{0,3})";
	
	private static final Pattern pattern = Pattern.compile(REGEX);
	

	/**
	 * Return the safari user agent stripping out 
	 * 	- all the chararcters between U; and Safari/xxx
	 *	
	 *  e.g Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_4_11; fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.1 Safari/525.18
	 * 		becomes
	 * 		Mozilla/5.0 (Macintosh Safari/525
	 * 
	 * @param string $userAgent
	 * @return string
	 */
	public String normalize(String userAgent) {
		String normalizedUserAgent = null;
		try {
			Matcher m = pattern.matcher(userAgent);
			if (m.find() && m.groupCount()>2) {
				String firstPart = userAgent.substring(0,userAgent.indexOf(m.group(2))+1);
				String secondPart = userAgent.substring(userAgent.indexOf(m.group(3)),userAgent.indexOf(m.group(3))+m.group(3).length());
				normalizedUserAgent = new StrBuilder(firstPart).append(secondPart).toString();
				
			}
		} catch (Exception e) {
			normalizedUserAgent = new StrBuilder(userAgent).toString();
		}
		return normalizedUserAgent;
	}

}
